package com.googlecode.gaal.analysis.impl;

import java.util.Iterator;

import com.googlecode.gaal.analysis.api.Filter;
import com.googlecode.gaal.analysis.api.IntervalSetBuilder;
import com.googlecode.gaal.data.api.Corpus;
import com.googlecode.gaal.suffix.api.EmbeddedSuffixTree.EmbeddedInterval;
import com.googlecode.gaal.suffix.api.IntervalTree.Interval;
import com.googlecode.gaal.suffix.api.LinearizedSuffixTree;
import com.googlecode.gaal.suffix.impl.LinearizedSuffixTreeImpl;

public class ConcurrentAnalyser extends Analyser {

    public ConcurrentAnalyser(final Corpus<String> srcCorpus, final Corpus<String> dstCorpus) {
        super(srcCorpus, dstCorpus, false);
        Stopwatch stopwatch = null;
        if (Aligner.isVerbose()) {
            stopwatch = new Stopwatch();
            stopwatch.start();
        }

        Runnable srcLSTBuilder = new Runnable() {
            @Override
            public void run() {
                srcLST = new LinearizedSuffixTreeImpl(srcSequence, srcCorpus.alphabetSize());
            }
        };

        Thread srcThread = new Thread(srcLSTBuilder);
        srcThread.start();

        if (dstCorpus != null) {
            Runnable dstLSTBuilder = new Runnable() {
                @Override
                public void run() {
                    dstLST = new LinearizedSuffixTreeImpl(dstSequence, dstCorpus.alphabetSize());
                }
            };

            Thread dstThread = new Thread(dstLSTBuilder);
            dstThread.start();

            try {
                dstThread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        try {
            srcThread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        if (stopwatch != null) {
            System.out.printf("constructed suffix arrays in %s\n", stopwatch);
        }
    }

    @Override
    protected <C extends Interval> Aligner<C> getAligner(IntervalVectorBuilder<C> vectorBuilder,
            Iterator<C> srcIterator, Iterator<C> dstIterator, Corpus<String> srcCorpus, Corpus<String> dstCorpus,
            double minSimilarity, int alignmentsNumber, int minVectorSize) {
        return new ConcurrentAligner<C>(vectorBuilder, srcIterator, dstIterator, srcCorpus, dstCorpus, minSimilarity,
                alignmentsNumber, minVectorSize);
    }

    @Override
    protected Iterable<EmbeddedInterval> getContextExtractor(LinearizedSuffixTree lst, Corpus<String> corpus,
            IntervalSetBuilder intervalSetBuilder, Filter<EmbeddedInterval> contextFilter, int windowSize) {
        return new ConcurrentEmbeddedContextExtractor(lst, corpus, intervalSetBuilder, contextFilter, windowSize);
    }
}
